<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="com.jiadakeji.ppm.modules.sys.utils.*" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>

<head>
    <title>发票预览</title>
    <meta name="decorator" content="default"/>
    <script src="${ctxStatic}/jquery-form/jquery.form.js" type="text/javascript"></script>

    <script src="${ctxStatic}/jquery-ui/jquery-ui.js" type="text/javascript"></script>
    <link href="${ctxStatic}/jquery-ui/jquery-ui.css" rel="stylesheet">

    <link href="${ctxStatic}/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
    <link href="${ctxStatic}/css/animate.min.css" rel="stylesheet">
    <link href="${ctxStatic}/css/common.css" rel="stylesheet">
    <link href="${ctxStatic}/css/style.min.css?v=4.0.0" rel="stylesheet">
    <OBJECT ID=sk
            CLASSID="clsid:003BD8F2-A6C3-48EF-9B72-ECFD8FC4D49F"
            codebase="NISEC_SKSCX.ocx#version=1,0,0,1" width=0 height=0>
    </OBJECT>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#invioceForm").height($(window).height() - 35);
            //$("#name").focus();
            $("#inputForm").validate({
                submitHandler: function (form) {

                },
                errorContainer: "#messageBox",
                errorPlacement: function (error, element) {
                    $("#messageBox").text("输入有误，请先更正。");
                    if (element.is(":checkbox") || element.is(":radio") || element.parent().is(".input-append")) {
                        error.appendTo(element.parent().parent());
                    } else {
                        error.insertAfter(element);
                    }
                }
            });
        });
    </script>
    <style>
        body {
            background: #FFF;
        }

        .fixed {
            table-layout: auto;
            width: 70%;
            text-align: center;
        }

        .collapse {
            border-collapse: collapse;
            border: 1px solid black;
            overflow: scroll;
        }

        caption {
            font-size: 1.5em;
            font-weight: bolder;
            padding: 0 10px;
        }

        .table-top {
            font-size: .7em;
            font-weight: normal;
            width: 100%;
            display: flex;
            display: -webkit-flex;
            justify-content: space-between;
            -webkit-justify-content: space-between;
            margin-bottom: 0em;
        }

        .table-top li {
            display: inline-block
        }

        table th {
            padding: 5px;
        }

        table td {
            padding: 5px;
            height: 1.5em;
        }

        .text-left {
            text-align: left;
            width: 100px;

        }
        .ui-autocomplete {
            max-height: 500px;
            overflow-y: auto;
            /* 防止水平滚动条 */
            overflow-x: hidden;
        }
        /* IE 6 不支持 max-height
         * 我们使用 height 代替，但是这会强制菜单总是显示为那个高度
         */
        * html .ui-autocomplete {
            height: 500px;
        }
    </style>
</head>

<body>

<form:form id="invioceForm" modelAttribute="fillInvioce" action="${ctx}/invioce/filling" method="post"
           class="form-horizontal" style="overflow: auto;width:98%;">
    <form:hidden path="content.kpzdbs" value="${counter}"/>
    <input type="hidden" id="settleId" name="settleId" />
    <form:hidden path="content.fpqqlsh" value="${feeReceive.id}"/>
    <form:hidden path="content.kplx" value="0"/>
    <form:hidden path="content.qdbz" value="0"/>
    <form:hidden path="content.zsfs" value="0"/>
    <table border="1" class="collapse fixed" align="center">
        <caption>
            <span style="margin-bottom: 10px;display: inline-block;">发票信息填写</span>
            <div class="table-top">
                <li><label>发票类型</label>
                    <span>
                            <input id="content.fplxdm1" name="content.fplxdm" onclick="changeInvioceType()"
                                   class="required" type="radio" value="007" checked="checked"/>
                            <label for="content.fplxdm1">增值税普通票</label>
                        </span>
                    <span>
                            <input id="content.fplxdm2" name="content.fplxdm" onclick="changeInvioceType()"
                                   class="required special-tag" type="radio" value="004"/>
                            <label for="content.fplxdm2">增值税专用票</label>
                        </span>
                <li style="margin-right: 8%;"><label>特殊票种</label>
                    <span><input id="content.tspz1" name="content.tspz" class="required" type="radio" value="00"
                                 checked="checked"/><label for="content.tspz1">不是</label></span><span><input
                            id="content.tspz2" name="content.tspz" class="required" type="radio" value="01"/><label
                            for="content.tspz2">农产品销售</label></span><span><input id="content.tspz3" name="content.tspz"
                                                                                 class="required" type="radio"
                                                                                 value="02"/><label for="content.tspz3">农产品收购</label></span><span><input
                            id="content.tspz4" name="content.tspz" class="required" type="radio" value="06"/><label
                            for="content.tspz4">抵扣通行费</label></span><span><input id="content.tspz5" name="content.tspz"
                                                                                 class="required" type="radio"
                                                                                 value="07"/><label for="content.tspz5">其它通行费</label></span>
                </li>
            </div>
        </caption>
        <tbody>
        <tr>
            <td rowspan="4" style="width: 20px;">购买方</td>
            <td class="text-left">名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称：</td>
            <td class="text-left" colspan="10">
                <form:input path="content.ghdwmc" value="" id="mingc"
                            class="input-xlarge" cssStyle="float: left;"/>
                <p id="showp1" style="color: #ff0000;float: left;margin-bottom: 0px;margin-top: 4px;margin-left: 20px;"
                   class="invisible">名字不能为空</p>
            </td>
            <td rowspan="4" style="width: 20px;">密码区</td>
            <td rowspan="4" colspan="10"></td>
        </tr>
        <tr>
            <td class="text-left">纳税人识别号：</td>
            <td class="text-left" colspan="10">
                <form:input path="content.ghdwsbh" value="" id="shib"
                            class="input-xlarge" cssStyle="float: left;"/>
                <p id="showp2" style="color: #ff0000;float: left;margin-bottom: 0px;margin-top: 4px;margin-left: 20px;"
                   class="invisible">识别号不能为空</p>
            </td>
        </tr>
        <tr>
            <td class="text-left">地 &nbsp;址、电&nbsp;话：</td>
            <td class="text-left" colspan="10">
                <form:input path="content.ghdwdzdh" value="" id="diz"
                            class="input-xlarge" cssStyle="float: left;"/>
                <p id="showp3" style="color: #ff0000;float: left;margin-bottom: 0px;margin-top: 4px;margin-left: 20px;"
                   class="invisible">联系方式不能为空</p>
            </td>
        </tr>
        <tr>
            <td class="text-left">开户行及账号：</td>
            <td class="text-left" colspan="10">
                <form:input path="content.ghdwyhzh" value="" id="kaih"
                            class="input-xlarge" cssStyle="float: left;"/>
                <p id="showp4" style="color: #ff0000;float: left;margin-bottom: 0px;margin-top: 4px;margin-left: 20px;"
                   class="invisible">开户行及账号不能为空</p>
            </td>
        </tr>
        <tr>
            <td colspan="8">货物或应税劳务、服务名称</td>
            <td colspan="2">规格型号</td>
            <td colspan="1">单位</td>
            <td colspan="2">数 量</td>
            <td colspan="2">单 价</td>
            <td colspan="3">金 额</td>
            <td>税率</td>
            <td colspan="3">税 额</td>
        </tr>
        <c:forEach items="${goodsList}" var="goods" varStatus="count">
            <tr>
                <form:hidden path="content.salesGoods.group[${count.index}].xh" value="${goods.xh}"/>
                <form:hidden path="content.salesGoods.group[${count.index}].fphxz" value="0"/>
                <form:hidden path="content.salesGoods.group[${count.index}].spsm"/>
                <td colspan="8"><form:input path="content.salesGoods.group[${count.index}].spmc"
                                            class="input-medium invoice-row-count1${count.index}"/></td>
                <td colspan="2"><form:input path="content.salesGoods.group[${count.index}].ggxh"
                                            class="input-medium invoice-row-count2${count.index}"/></td>
                <td><form:input path="content.salesGoods.group[${count.index}].dw"
                                class="input-medium invoice-row-count3${count.index}"/></td>
                <td colspan="2"><form:input path="content.salesGoods.group[${count.index}].spsl"
                                            class="input-medium invoice-row-count4${count.index}"/></td>
                <td colspan="2"><form:input path="content.salesGoods.group[${count.index}].dj"
                                            class="input-medium invoice-row-count5${count.index}"/></td>
                <td colspan="3"><form:input path="content.salesGoods.group[${count.index}].je"
                                            class="input-medium invoice-row-count6${count.index}"/></td>
                    <%--<td><form:input path="content.salesGoods.group[${count.index}].sl" value='${goods.sl eq "0.0"? "0":goods.sl}' class="input-medium invoice-row-count7${count.index}"/></td>--%>
                <td>
                    <form:select path="content.salesGoods.group[${count.index}].spbm" onchange="selectChange(${count.index})"
                            class="input-medium invoice-row-count7${count.index}" style="padding: 0px;border: 0px;">
                        <option value="">
                            --请选择--
                        </option>
                       <form:options items="${taxRateList}" itemLabel="spName" itemValue="spbm" htmlEscape="false"/>
                    </form:select>
                </td>
                <td colspan="3"><form:input path="content.salesGoods.group[${count.index}].se"
                                            class="input-medium  invoice-row-count8${count.index}"/></td>
                <form:hidden path="content.salesGoods.group[${count.index}].hsbz" value="0"/>
                <form:hidden path="content.salesGoods.group[${count.index}].zxbm"/>
                <form:hidden path="content.salesGoods.group[${count.index}].yhzcbs" value="${goods.yhzcbs}"/>
                <form:hidden path="content.salesGoods.group[${count.index}].lslbs" value="${goods.lslbs}"/>
                <form:hidden path="content.salesGoods.group[${count.index}].zzstsgl" value="${goods.zzstsgl}"/>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="8">合计</td>
            <td colspan="2"></td>
            <td></td>
            <td colspan="2"></td>
            <td colspan="2"></td>
            <td colspan="3"><form:input path="content.hjje" id="totalamount" value=" ${preContent.hjje}"
                                        class="input-medium"/></td>
            <td></td>
            <td colspan="3"><form:input path="content.hjse" id="totaltax" value=" ${preContent.hjse} "
                                        class="input-medium"/></td>
        </tr>
        <tr>
            <td colspan="8">价税合计（大写）</td>
            <td style="text-align: left" colspan="11"><input name="moneySum" value=" ${moneySum}" class="input-medium"/>
            </td>
            <td style="border-right: none;border-left: none;width: 35px;">(小写)</td>
            <td style="border-left: none;" colspan="2"><form:input path="content.jshj" id="sum"
                                                                   value=" ${preContent.jshj}"
                                                                   class="input-small"/></td>
        </tr>
        </tbody>
        <tfoot>
        <tr>
            <td rowspan="4" style="width: 20px;">销售方</td>
            <td class="text-left">名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称：</td>
            <td class="text-left" colspan="10"><form:input path="content.xhdwmc" value=" ${map.xhdwmc} "
                                                           class="input-xlarge"/></td>
            <td rowspan="4" style="width: 20px;">备注</td>
            <td rowspan="4" colspan="10" class="text-left"><form:textarea path="content.bz" value="${preContent.bz}"
                                                                          class="input-medium" rows="4"
                                                                          maxlength="255"/></td>
        </tr>
        <tr>
            <td class="text-left">纳税人识别号：</td>
            <td class="text-left" colspan="10"><form:input path="content.xhdwsbh" value="${map.xhdwsbh}"
                                                           class="input-xlarge"/></td>
        </tr>
        <tr>
            <td class="text-left">地 &nbsp;址、电&nbsp;话：</td>
            <td class="text-left" colspan="10"><form:input path="content.xhdwdzdh" value="${map.xhdwdzdh}"
                                                           class="input-xlarge"/></td>
        </tr>
        <tr>
            <td class="text-left">开户行及账号：</td>
            <td class="text-left" colspan="10"><form:input path="content.xhdwyhzh" value="${map.xhdwyhzh}"
                                                           class="input-xlarge"/></td>
        </tr>
        </tfoot>
    </table>
    <div style="width: 80%;">
        <div class="table-top" style="font-size: .9em;margin-top: .8em;margin-left: 13%;">
            <li>收&nbsp;&nbsp;款&nbsp;&nbsp;人:<form:input path="content.skr" value="${preContent.skr}"/></li>
            <li>复&nbsp;&nbsp;核:<form:input path="content.fhr" value="${preContent.fhr}"/></li>
            <li>开&nbsp;&nbsp;票&nbsp;&nbsp;人:<form:input path="content.kpr" value="${preContent.kpr}"
                                                        class="input-medium"/></li>
            <li style="margin-right: 8%;">销&nbsp;&nbsp;售&nbsp;&nbsp;方:&nbsp;&nbsp;（章）</li>
        </div>
    </div>
    <form:hidden path="content.kce"/>
    <form:hidden path="content.tzdbh"/>
    <form:hidden path="content.yfpdm"/>
    <form:hidden path="content.yfphm"/>
    <div style="width: 100%; text-align: center; margin: 35px 0px 25px 0px;">
        <button type="button" onclick="fillingInvioce()" class="btn btn-warning">发票开具</button>
        <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
            <%--<input class="btn" type="button" value="cess" onclick="judgeIsNull()"/>--%>
    </div>

</form:form>

<script type="text/javascript">

    //名称不能为空
    $("#mingc").blur(function mingc() {
        var name = $("#mingc").val();
        if (name == '') {
            $("#showp1").removeClass("invisible");
            $("#showp1").addClass("visible");
        } else {
            $("#showp1").addClass("invisible")
        }
    });

    //纳税人识别号不能为空
    $("#shib").blur(function shib() {
        if ($(".special-tag").attr('checked'))
            var shib = $("#shib").val();
        if (shib == '') {
            $("#showp2").removeClass("invisible");
            $("#showp2").addClass("visible");
        } else {
            $("#showp2").addClass("invisible")
        }
    });

    //地  址、电 话不能为空
    $("#diz").blur(function diz() {
        if ($(".special-tag").attr('checked'))
            var diz = $("#diz").val();
        if (diz == '') {
            $("#showp3").removeClass("invisible");
            $("#showp3").addClass("visible");
        } else {
            $("#showp3").addClass("invisible")
        }
    });

    //开户行及账号不能为空
    $("#kaih").blur(function kaih() {
        if ($(".special-tag").attr('checked'))
            var kaih = $("#kaih").val();
        if (kaih == '') {
            $("#showp4").removeClass("invisible");
            $("#showp4").addClass("visible");
        } else {
            $("#showp4").addClass("invisible")
        }
    });

    //税率改变做计算
    function selectChange(index) {
        var count = $(".invoice-row-count4" + index).val();
        var price = $(".invoice-row-count5" + index).val();
        var taxText = $(".invoice-row-count7" + index).find("option:selected").text();
        var tax = taxText.substr(taxText.indexOf(':') + 1,4);
        // console.log(tax)
        var jine = 0;
        var shuie = 0;
        // console.log("count=" + count);
        // console.log("price=" + price);
        // console.log(parseFloat(tax));
        if ((count != '') && (price != '') && (tax != '')) {
            var taxnum = parseFloat(tax);
            var oriall = count * price;
            // console.log(oriall);
            var all = oriall.toFixed(2);
            // console.log(all);
            var notaxcount = all / (taxnum + 1);
            var taxcount = all - notaxcount;
            var singleprice = price / (taxnum + 1);
            $(".invoice-row-count5" + index).val(singleprice.toFixed(10));
            $(".invoice-row-count6" + index).val(notaxcount.toFixed(2));
            $(".invoice-row-count8" + index).val(taxcount.toFixed(2));
            // console.log("税额" + taxcount);
            // console.log("金额" + notaxcount);
            // console.log("税后单价" + singleprice);
            taxnum = price = count = all = taxcount = notaxcount = singleprice = 0;
            for (var j = 0; j < 6; j++) {
                if (!isNaN(parseFloat($(".invoice-row-count6" + j).val()))) {
                    jine = jine + parseFloat($(".invoice-row-count6" + j).val());
                }
                if (!isNaN(parseFloat($(".invoice-row-count8" + j).val()))) {
                    shuie = shuie + parseFloat($(".invoice-row-count8" + j).val());
                }
            }
            // console.log("金额："+jine);
            $("#totalamount").val(jine.toFixed(2));
            $("#totaltax").val(shuie.toFixed(2));
            $("#sum").val((jine + shuie).toFixed(2));
        }
    }

    //判断名称、金额、税率和税额是否一起填写
    function judgeIsNull() {
        var kname, kjine, kshuilv, kshuie, kflag, x;
        kflag = 0;
        for (var k = 0; k < 6; k++) {
            kname = $(".invoice-row-count1" + k).val();
            kjine = $(".invoice-row-count6" + k).val();
            kshuilv = $(".invoice-row-count7" + k).find("option:selected").val();
            kshuie = $(".invoice-row-count8" + k).val();
            // console.log(kname);
            // console.log(kjine);
            //  console.log(kshuilv);
            // console.log(kshuie);
            if (((kname != '') && (kjine != '') && (kshuilv != 0) && (kshuie != '')) || ((kname == '') && (kjine == '') && (kshuilv == 0) && (kshuie == ''))) {
            } else {
                kflag = 1;
            }
            // console.log(k+"---"+kflag);
        }
        return kflag;
    }

    //提交
    function fillingInvioce() {
        var queryString = $('#invioceForm').serializeArray();
        // console.log(queryString)
        // SetParameter();
//            SetMargin();
        if ($(".special-tag").attr('checked')) {
            if (($("#mingc").val() == '') || ($("#shib").val() == '') || ($("#diz").val() == '') || ($("#kaih").val() == '')) {
                alert("请补全信息！");
            } else {
                if (judgeIsNull() == 0) {

                    $.ajax({
                        type: "POST",  //提交方式
                        url: "${ctx}/invioce/blankFilling",//路径
                        data: queryString,
                        success: function (result) {//返回数据根据结果进行相应的处
                            SetParameter();
                            SetMargin();
                            invioceFIll(result);
                        }
                    })
                } else {
                    alert("名称，金额，税率和税额必须全填或者全不填！");
                }
            }
        } else {
            if ($("#mingc").val() == '') {
                alert("请输入名字！");
            } else {
                if (judgeIsNull() == 0) {
                    SetParameter();
                    SetMargin();
                    $.ajax({
                        type: "POST",  //提交方式
                        url: "${ctx}/invioce/blankFilling",//路径
                        data: queryString,
                        success: function (result) {//返回数据根据结果进行相应的处
                            invioceFIll(result);
                        }
                    })
                } else {
                    alert("名称，金额，税率和税额必须全填或者全不填！");
                }
            }
        }
    }

    function SetMargin() {
        $.ajax({
            async: false,
            type: "POST",  //提交方式
            url: "${ctx}/invioce/getMarginProperty",//路径
            data: {
                "fplxdm": $("input[name='content\\.fplxdm']:checked").val()
            },
            success: function (result) {//返回数据根据结果进行相应的处
                marginSet(result);
            }
        });
    }

    function marginSet(result) {
        var sInputInfo = result;
        console.log(sInputInfo);
        try {
            ret = sk.Operate(sInputInfo);
            console.log(ret);
        }
        catch (e) {
            alert(e.message + ",errno:" + e.number);
        }
    }

    function SetParameter() {
        var sInputInfo =
            "<?xml version=\"1.0\" encoding=\"gbk\"?>\r\n" +
            "<business id=\"20001\" comment=\"参数设置\">\r\n" +
            "<body yylxdm=\"1\">\r\n" +
            "<servletip>124.225.17.145</servletip>\r\n" +
            "<servletport>8082</servletport>\r\n" +
            "<keypwd>88888888</keypwd>\r\n" +
            "</body>\r\n" +
            "</business>";
        try {
            ret = sk.Operate(sInputInfo);
            console.log(ret);
        }
        catch (e) {
            alert(e.message + ",errno:" + e.number);
        }
    }

    function invioceFIll(result) {
        var sInputInfo = result;
        console.log(sInputInfo);
        try {
            ret = sk.Operate(sInputInfo);
            console.log(ret);
            doPrinter(ret);
        }
        catch (e) {
            alert(e.message + ",errno:" + e.number);
        }
    }


    function doPrinter(requsetXml) {
        var xml = requsetXml;
        var kpzdbs = $("#content\\.kpzdbs").val();
        $.ajax({
            type: "POST",  //提交方式
            url: "${ctx}/invioce/doPrinter",//路径
            data: {
                "requestXml": xml,
                "fplxdm": $("input[name='content\\.fplxdm']:checked").val(),
                "kpzdbs": kpzdbs
            },
            success: function (result) {//返回数据根据结果进行相应的处理
                alert("请核对发票代码、发票号码与纸质发票一致：发票代码" + result.fpdm + ";发票号码" + result.fphm);
                if (result.code == "0") {
                    printetInvioce(result.xml);
                } else {
                    alert("发生错误了！！" + result.xml);
                }
            }
        })
    }

    function printetInvioce(result) {
        var sInputInfo = result;
        console.log(sInputInfo);
        try {
            ret = sk.Operate(sInputInfo);
            alert(ret);
        }
        catch (e) {
            alert(e.message + ",errno:" + e.number);
        }
    }
</script>

<script type="text/javascript">
    var cache = {};
    $( "#mingc" ).autocomplete({
        source: function(request, response ) {
            $("#settleId").val("");
            var term = request.term;
            if ( term in cache ) {
                response( $.map( cache[ term ], function( item ) {
                    return {
                        label:item.settleName,
                        aa:item.id
                    }
                }));
                return;
            }
            $.ajax({
                url: "${ctx}/threeuserinfo/setteleUser/findCompanyUser",
                dataType: "json",
                data:{
                    settleName: $("#mingc").val()
                },
                success: function( data ) {
                    cache[ term ] = data;
                    // console.log("----"+JSON.stringify(data));
                    response( $.map( data, function( item ) {
                        return {
                            label:item.settleName,
                            aa:item.id
                        }
                    }));
                }
            });
        },
        minLength: 1,

        select: function( event, ui ) {
            $.ajax({
                url: "${ctx}/threeuserinfo/setteleUser/getSetteleUser",
                dataType: "json",
                data:{
                    id: ui.item.aa
                },
                success: function( data ) {
                    $("#settleId").val(data.id);
                    $("#mingc").val(data.settleName);
                    $("#shib").val(data.taxCode);
                    $("#diz").val(data.embranchCode);
                    $("#kaih").val(data.billTypeId);
                }
            });



            // $("#mingc").val(ui.item.label);
            // $("#shib").val(ui.item.taxCode);
            // $("#diz").val(ui.item.embranchCode);
            // $("#kaih").val(ui.item.billTypeId);
        }
    });
</script>
</body>


</html>